import Router from "@koa/router";
import { AppError, asleep } from "common";
import { DEFAULT_AVATAR } from "data";
import { z } from "zod";

const router = new Router();

const ME = {
  username: "admin",
  avatar: DEFAULT_AVATAR,
};

router.get("/profile", async (ctx) => {
  const token = ctx.cookies.get("token");
  if (token !== "admin") {
    throw AppError.unauthenticated();
  }

  await asleep(1000);

  ctx.body = ME;
});

const LOGIN_PAYLOAD_SCHEMA = z.object({
  username: z.string().min(3).max(30),
  password: z.string().min(10).max(64),
});

router.post("/login", async (ctx) => {
  const result = LOGIN_PAYLOAD_SCHEMA.safeParse(ctx.request.body);
  if (result.error) {
    throw result.error;
  }

  const { username, password } = result.data;

  if (username === "admin" && password.length >= 12) {
    await asleep(1000);
    ctx.body = ME;
    ctx.cookies.set("token", username, { maxAge: 1000 * 60 * 60 * 4, httpOnly: true });
    return;
  }

  throw AppError.badRequest("Username or password invalid.");
});

router.post("/logout", (ctx) => {
  ctx.cookies.set("token", "", { maxAge: 0, httpOnly: true });
  ctx.body = "";
});

export default router;
